package com.infore.dataReceiving.controller;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import com.infore.dataReceiving.constant.Constants;
import com.infore.dataReceiving.core.enums.Air212InstructionsTypeEnum;
import com.infore.dataReceiving.entity.BackControlLog;
import com.infore.dataReceiving.enums.ResultStatus;
import com.infore.dataReceiving.repository.IBackControlLogRepository;
import com.infore.dataReceiving.util.Air212InstructionsHandleUtil;
import com.infore.dataReceiving.util.CRCCheck;
import com.infore.dataReceiving.util.ResultEntity;
import io.netty.channel.ChannelHandlerContext;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Controller
public class Air212BackControlInstructionController {
	
	private static final Logger log = LoggerFactory.getLogger(Air212BackControlInstructionController.class); 
	
	@Autowired
	private IBackControlLogRepository iBackControlLogRepository;
	
	@Autowired
	RestTemplate restTemplate;
	
	@ApiOperation(value = "发送反控指令", notes = "发送反控指令")
    @ApiImplicitParams({@ApiImplicitParam(name = "mn", value = "站点mn号", paramType = "query", required = true, dataType = "String"),
    	    @ApiImplicitParam(name = "password", value = "站点密码", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cn", value = "指令编号", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "condition", value = "其他条件，逗号分隔", paramType = "query", required = true, dataType = "String")
    })
	@RequestMapping(value = "/air212SendBackControl", method = RequestMethod.GET)
	@ResponseBody
	public ResultEntity sendBackControl(@Param("mn")String mn,@Param("password")String password,
			@Param("cn")String cn,@Param("condition")String condition) throws Exception {
		ChannelHandlerContext ctx = Air212InstructionsHandleUtil.cMap.get("air_"+mn);
		if(ctx==null) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("设备不在线，请稍后再试！"); 
		}
		if(mn==null||"".equals(mn)) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("站点MN不允许为空!");
		}
		if(password==null||"".equals(password)) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("站点密码不允许为空!");
		}
		if(cn==null||"".equals(cn)) {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("指令编号不允许为空!");
		}
		String ycip = null;
		try {
//			ycip = InetAddress.getLocalHost().getHostAddress();
			ycip = Air212InstructionsHandleUtil.getInetAddress("eth3", 4);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println("本机ip地址为："+ycip);
        
		SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		Date date = new Date();
		String qn = sdfDateFormat.format(date);
		
		if(Air212InstructionsTypeEnum.air212_2051.getCn().equals(cn)) {//取污染物分钟历史数据
//			if(Air212InstructionsHandleUtil.dateMap.get(mn+"backControl")!=null){
//				return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("系统正在执行补数指令，请稍后再试!");
//			}
			String[] times = condition.split(",");
			Timestamp begin = Air212InstructionsHandleUtil.getTimestamp(times[0].split("=")[1]);
			Timestamp end = Air212InstructionsHandleUtil.getTimestamp(times[1].split("=")[1]);
			if(end.getTime()-begin.getTime()>3*24*60*60*1000) {
				return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("补数时长不允许超过3天!");
			}
//			else {
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("begin", begin);
//				map.put("end", end);
//				map.put("mn", mn);
//				Air212InstructionsHandleUtil.dateMap.put(mn+"backControl", map);
//			}
			//市平台处理与区县平台数据补遗对接
			if("10.33.50.69".equals(ycip)&&("LH001510200026".equals(mn)||"LH001510200027".equals(mn)||"LH001510200028".equals(mn)
	    			||"LH001510200022".equals(mn)||"LH001510200023".equals(mn)||"LH001510200024".equals(mn))) {
				try {
					String msg = getDataBack(mn,condition);
					String datas = "QN="+qn+";ST=32;CN="+cn+";PW="+password+";MN="+mn+";Flag=5;CP=&&"+condition+"&&";
					int dataLength = datas.length();//数据段长度
					String crc = CRCCheck.crc16(datas, dataLength);
					String dataLengthString = Air212InstructionsHandleUtil.getDataLengthString(dataLength+"");
					String returnInfo = "##"+dataLengthString+datas+crc+"\r\n";
					BackControlLog log = new BackControlLog();
					log.setQn(qn);
					log.setMn(mn);
					log.setCn(cn);
					log.setDescription(Air212InstructionsTypeEnum.air212_2051.getMsg());
					log.setOperationUser("admin");
					log.setOperationTime(new Timestamp(date.getTime()));
					log.setIp("127.0.0.1");
					log.setContent(returnInfo);
					iBackControlLogRepository.save(log);
					return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS).setInfo("指令已经发送给下级平台，下级平台返回结果为："+msg);
				} catch (Exception e) {
					System.out.println("无法连接远程服务器！");
					e.printStackTrace();
					return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("无法连接远程服务器!");
				}
			}else {
				boolean flag = send(qn,"2011",password,mn,Air212InstructionsTypeEnum.air212_2051.getMsg(),date,ctx,condition);
				if(flag) {
					return new ResultEntity(ResultStatus.SUCCESS, Constants.DEAL_SUCCESS).setInfo("指令发送成功,请查看日志确认反控结果!");
				}else {
					return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("客户端链接异常，请联系管理员!");
				}
			}
		}else {
			return new ResultEntity(ResultStatus.ERROR, Constants.DEAL_FAILUE).setInfo("暂时不支持该指令,请联系管理员添加!");
		}
	}
	public Boolean send(String qn,String cn,String password,String mn,String description,
			Date date,ChannelHandlerContext ctx,String dataArea) {
		String datas = "QN="+qn+";ST=32;CN="+cn+";PW="+password+";MN="+mn+";Flag=5;CP=&&"+dataArea+"&&";
		int dataLength = datas.length();//数据段长度
		String crc = CRCCheck.crc16(datas, dataLength);
		String dataLengthString = Air212InstructionsHandleUtil.getDataLengthString(dataLength+"");
		String returnInfo = "##"+dataLengthString+datas+crc+"\r\n";
		try {
			ctx.channel().writeAndFlush(returnInfo);
			System.out.println("取污染物分钟历史数据成功！");
			BackControlLog log = new BackControlLog();
			log.setQn(qn);
			log.setMn(mn);
			log.setCn(cn);
			log.setDescription(description);
			log.setOperationUser("admin");
			log.setOperationTime(new Timestamp(date.getTime()));
			log.setIp("127.0.0.1");
			log.setContent(returnInfo);
			iBackControlLogRepository.save(log);
			return true;
		} catch (Exception e) {
			Air212InstructionsHandleUtil.cMap.remove("air_"+mn);
			return false;
		}
	}
	
	
	 /**
		 * 数据回补
		 */
		public String getDataBack(String mn,String condition){
	    	
			HttpHeaders requestHeaders = new HttpHeaders();
	        @SuppressWarnings("rawtypes")
	        HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
	        String ycip = null;
	    	if("LH001510200022".equals(mn)||"LH001510200023".equals(mn)||"LH001510200024".equals(mn)) {
	    		ycip = "10.33.52.13";
	    	}
	    	if("LH001510200026".equals(mn)||"LH001510200027".equals(mn)||"LH001510200028".equals(mn)) {
	    		ycip = "10.33.69.200";
	    	}
	        String url = "http://"+ycip+":61001/DataReceiving-Service/air212SendBackControl"
	        		+ "?password=123456"
	        		+ "&cn=2051"
	        		+ "&mn="+mn
	        		+"&condition="+condition;
	        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
	        return responseEntity.getBody();
			
		};
	
	

}
